package com.ccrfid.rmc6.util;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NetUtil {
    //获取本地主机IP地址
    public static Set<String> getLocalIpAddresses() {
        Set<String> ipSet = new HashSet<>();
        try {
            String localHostName = InetAddress.getLocalHost().getHostName();
            InetAddress[] inetAddresses = InetAddress.getAllByName(localHostName);
            for (InetAddress net : inetAddresses) {
                if (net.isSiteLocalAddress()) {
                    ipSet.add(net.getHostAddress());
                }
            }
        } catch (UnknownHostException ex) {
            ex.printStackTrace();
        }
        return ipSet;
    }

    //获取两个IP地址的相似度
    public static int getIPMatchDegree(String ip, String ip2) {
        int shortLength = ip.length() > ip2.length() ? ip2.length() : ip.length();
        for (int i = 0; i < shortLength; i ++) {
            if (ip.charAt(i) != ip2.charAt(i)) {
                return i;
            }
        }
        return shortLength;
    }

    //获取与clientIP最匹配的IP地址
    public static String getMatchIPAddr(String clientIpAddr, String ip, String ip2) {
        if (ip2 == null || ip2.isEmpty()) {
            return ip;
        }
        if (clientIpAddr.equals("127.0.0.1") || clientIpAddr.equals("0:0:0:0:0:0:0:1")) {
            return ip;
        } else {
            int degree = getIPMatchDegree(clientIpAddr, ip);
            int degree2 = getIPMatchDegree(clientIpAddr, ip2);
            if (degree >= degree2) {
                return ip;
            } else {
                return ip2;
            }
        }
    }

    public static String getURLIp(String url) {
        Pattern pattern = Pattern.compile("//*.*.*.*:");
        Matcher matcher = pattern.matcher(url);
        if (matcher.find()) {
            String ip = matcher.group(0);
            return ip.substring(2, ip.length() - 1);
        }
        return "";
    }
}
